package at.jku.pervasive.recognition;

import java.io.StringReader;
import java.util.Date;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class GestureEvent extends Gesture
{

	private static XMLOutputter outputter = new XMLOutputter();
	private static SAXBuilder saxBuilder = new SAXBuilder();

	private GestureEventType eventType;
	private long durartion;

	public static GestureEvent getGestureEvent(String gestureEventStringXml)
	{
		try
		{
			Document doc = saxBuilder.build(new StringReader(gestureEventStringXml));
			Element gestureEventEl = doc.getRootElement();

			String typeStr = gestureEventEl.getAttributeValue("type");
			GestureType gestureType = GestureType.valueOf(typeStr);

			String eventTypeStr = gestureEventEl.getAttributeValue("eventType");
			GestureEventType gestureEventType = GestureEventType.valueOf(eventTypeStr);

			GestureEvent gestureEvent = new GestureEvent(gestureType);
			gestureEvent.setEventType(gestureEventType);
			switch (gestureEventType)
			{
				case GESTURE_STARTED:
				{
					String timestampStr = gestureEventEl.getAttributeValue("timestamp");
					Long timestamp = Long.valueOf(timestampStr);
					gestureEvent.setTimestamp(new Date(timestamp.longValue()));
					break;
				}
				case GESTURE_FINISHED:
					String durationStr = gestureEventEl.getAttributeValue("duration");
					Long duration = Long.valueOf(durationStr);
					gestureEvent.setDurartion(duration.longValue());
					break;
			}

			return gestureEvent;
		} catch (Exception e)
		{
			throw new IllegalArgumentException("could not parse the gestureEvent xml string", e);
		}
	}

	private void setTimestamp(Date date)
	{
		this.timestamp = date;
	}

	public GestureEvent(GestureType gestureType)
	{
		super(gestureType);
	}

	public GestureEvent(GestureType gestureType, Date timestamp)
	{
		super(gestureType, timestamp);
	}

	public GestureEventType getEventType()
	{
		return eventType;
	}

	public void setEventType(GestureEventType eventType)
	{
		this.eventType = eventType;
	}

	public long getDurartion()
	{
		return durartion;
	}

	public void setDurartion(long durartion)
	{
		this.durartion = durartion;
	}

	@Override
	public String toString()
	{
		Element eventEl = new Element("gesture");
		eventEl.setAttribute("type", gestureType.name());
		eventEl.setAttribute("eventType", eventType.name());

		if (GestureEventType.GESTURE_STARTED == eventType)
			eventEl.setAttribute("timestamp", Long.toString(timestamp.getTime()));
		else if (GestureEventType.GESTURE_FINISHED == eventType)
			eventEl.setAttribute("duration", Long.toString(durartion));

		return outputter.outputString(eventEl);
	}

}
